import PropTypes from '@/utils/PropTypes'
import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue'
import { Checkbox } from 'ant-design-vue'
import { uniq } from 'lodash'
import './index.less'
export default defineComponent({
  neme: 'AuthCom',
  props: {
    data: PropTypes.array().def([]),
    value: PropTypes.any().def([]),
    is_disable: PropTypes.bool().def(false),
    isShow: PropTypes.bool().def(true),
    fieldNames: PropTypes.object<{
      label: string
      value: string
      checked: boolean
    }>().def({
      label: '',
      value: '',
      checked: false,
    }),
  },
  emits: ['update:changAllList'],
  setup(props, { emit, slots }) {
    // 全选
    const checkedAll = ref<boolean>(false)
    const changAllList = ref<string[]>([])
    const changAll = (e: any) => {
      if (e.target.checked) {
        props.data.forEach((v: any) => (v.checked = true))
        changAllList.value = props.data.map((v: any) => v.id)
        uniq(changAllList.value)
      } else {
        props.data.forEach((v: any) => (v.checked = false))
        changAllList.value = []
      }
    }
    // 单选
    const change = (v: any) => {
      v.checked = !v.checked
      const index = changAllList.value.findIndex((item) => v.id == item)
      if (v.checked && index < 0) {
        changAllList.value.push(v.id)
      } else {
        changAllList.value.splice(index, 1)
      }
    }
    watch(
      () => props.value.length,
      (val) => {
        if (val > 0) {
          props.data.forEach((v: any) => {
            if (props.value.includes(v.id)) {
              v.checked = true
            }
            return v
          })
          changAllList.value = props.value
        }
      },
    )
    watch(
      () => changAllList.value.length,
      (val) => {
        checkedAll.value = val == props.data.length
        emit('update:changAllList', changAllList.value)
      },
    )
    onMounted(() => {
      console.log(changAllList.value, props.value, '---')
    })
    onUnmounted(() => {
      props.data.forEach((v: any) => (v.checked = false))
      changAllList.value = []
      console.log(changAllList.value, props.value)
      console.log('销毁了。。。')
    })
    return () => (
      <div class="auth-func-wapper">
        {props.isShow && (
          <div>
            <Checkbox onChange={changAll} checked={checkedAll.value} /> 全选
          </div>
        )}

        <div class="func-content-wapper">
          <div>
            <div class="func-item-box">
              {props.data.map((v: any) => (
                <div class="func-itme">
                  <Checkbox checked={v.checked} onChange={() => change(v)}>
                    {v[props.fieldNames.label]}
                  </Checkbox>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    )
  },
})
